﻿using Restful_Api.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core
     ;
using System.Runtime.InteropServices;
using System.Threading.Tasks;

namespace Restful_Api.Helpers
{
    /// <summary>
    /// IQueryable的扩展方法 用作排序
    /// </summary>
    public static class IQueryableExtensions
    {
        public static IQueryable<T> ApplySort<T>(this IQueryable<T> source,
            string orderBy, Dictionary<string, PropertMappingValue> mappingDictionary)
        {
            if (source == null)
                throw new ArgumentNullException(nameof(source));
            if (mappingDictionary == null)
                throw new ArgumentNullException(nameof(mappingDictionary));
            if (string.IsNullOrWhiteSpace(orderBy))
                return source;

            var orderByAfterSplit = orderBy.Split(',');
            foreach (var item in orderByAfterSplit.Reverse())
            {
                var trimItem = item.Trim();
                var orderDescending = trimItem.EndsWith(" desc");//是不是 desc结尾

                var indexOfFirstSpace = trimItem.IndexOf(" ");

                var proPertyName = indexOfFirstSpace == -1 ? trimItem : trimItem.Remove(indexOfFirstSpace);

                if (!mappingDictionary.ContainsKey(proPertyName))
                {
                    throw new ArgumentNullException($"没有找到key为{proPertyName}的映射");
                }

                var proertyMappingValue = mappingDictionary[proPertyName];
                if (proertyMappingValue == null)
                    throw new ArgumentNullException(nameof(proertyMappingValue));
                foreach (var item1 in proertyMappingValue.DestinationProperties.Reverse())
                {
                    if (proertyMappingValue.Revert)
                        orderDescending = !orderDescending;

                    source = source.OrderBy(item1 + (orderDescending ? " descending" : " ascending"));
                }
            }
            return source;
        }
    }
}
